//
//  QADetailViewController.m
//  CYWFrame
//
//  Created by Macx on 2017/9/26.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "QADetailViewController.h"

#import "Question.h"
#import "LZPictureBrowser.h"
#import "QAZoneTableViewCell.h"
#import "PostsTextViewController.h"
#import "HomeServer.h"
#import "ReplyCommentViewController.h"
#import "AlertShareView.h"
#import "UILabel+copy.h"
#import "PushPerHome.h"
#import "AliPayServer.h"

@interface QADetailViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, assign) NSInteger page; // 网络请求页数

@property (nonatomic, strong) NSMutableArray *answerArr; //答案数组

@end

@implementation QADetailViewController {
    
    UIView      *_headBgView;
    UITableView *_tableView;
    QAZoneTableViewCell *_cell;
    
    UIImageView *_headPic;
    UIImageView *_role;
    UILabel     *_nickName;
    UIImageView *_gender;
    UILabel     *_date;
    UIButton    *_focus;
    UILabel     *_title;
    UILabel     *_viewsCount;
    UIButton    *_money;
    UIView      *_sepView;
    
    Question    *_detailModel;
}


- (void)viewWillAppear:(BOOL)animated {
    if (self.page == 1) {
        [self GETAnswers];
    }
}

// 主页tableView是否滚动接收到通知
- (void)notificationPay:(NSNotification *)notification {
    NSLog(@"－－－－－问题详情页面付费答案接收到通知------");
    [self GETAnswers];
}

//移除广播监听。
-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationPay:) name:@"payAnswers" object:nil];
    
    self.page = 1;
    
    [self GETAnswerDetail];
    
    
//    [self GETAnswers];
    
//    [self refreshData];
    
}

- (void)shareClick:(UIButton *)sender {
    
    AlertShareView *alert = [[AlertShareView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    
    NSString *text = _detailModel.title;
//    if (text.length > 20) {
//        text = [text substringToIndex:20];
//    }
    
    NSString *img = @"http://parkinsonplus.oss-cn-shenzhen.aliyuncs.com/images/0.png";
    if (_detailModel.pics.count > 0) {
        img = _detailModel.pics[0];
    }
    
    NSDictionary *p = @{@"url":[NSString stringWithFormat:@"http://www.payoujia.com/mobile/wenda/details?id=%@", self.answerId],
                        @"title":@"帕友+ 百万帕友信赖的精神家园", //@"帕友+ 动态分享",
                        @"text":text,
                        @"img":img};
    
    NSLog(@"分享参数 %@", p);
    
    [alert initShow:p];
    
    //    [self.view addSubview:alert];
    
    UIWindow *window = [[UIApplication sharedApplication].delegate window];
    [window addSubview:alert];
}

#pragma mark ==========构建UI==========
- (void)buildUI {
    
    self.view.backgroundColor = UISeparatedColorRGB;
    
    self.navigationItem.title = @"问题详情";
    
//    UIBarButtonItem *shareBtn = [[UIBarButtonItem alloc] initWithTitle:@"分享" style:UIBarButtonItemStyleDone target:self action:@selector(shareClick:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"分享" style:UIBarButtonItemStyleDone target:self action:@selector(shareClick:)];
    
    // frame
    CGSize size2 = [LZCTools textSizeWithText:@"5小时之前" font:kUHSystemFontWithSize(12)];
    
    CGSize size3 = [LZCTools textSizeWithText:@"未关注" font:kUHSystemFontWithSize(13)];
    
    // 头部
    _headBgView = [[UIScrollView alloc] init];
    
    _headPic = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, SW(9), SW(9))];
    [_headBgView addSubview:_headPic];
    _headPic.layer.cornerRadius = SW(18);
    _headPic.layer.masksToBounds = YES;
    
    _role = [[UIImageView alloc] initWithFrame:CGRectMake(_headPic.x+_headPic.width/3*2, _headPic.y+_headPic.height/3*2, _headPic.width/3, _headPic.width/3)];
    [_headBgView addSubview:_role];
    
    _nickName = [[UILabel alloc] init];
    [_headBgView addSubview:_nickName];
    _nickName.font = kUHSystemFontWithSize(16);
    
    _gender = [[UIImageView alloc] init];
    [_headBgView addSubview:_gender];
    
    _date = [[UILabel alloc] initWithFrame:CGRectMake(_headPic.x+_headPic.width+10, _headPic.y+_headPic.height-size2.height, SW(2), size2.height)];
    [_headBgView addSubview:_date];
    _date.font = kUHSystemFontWithSize(12);
    _date.textColor = kBlackColor;
    
    _focus = [UIButton buttonWithType:UIButtonTypeCustom];
    [_headBgView addSubview:_focus];
    _focus.titleLabel.font = kUHSystemFontWithSize(13);
    [_focus setTitleColor:kWhiteColor forState:UIControlStateNormal];
//    CGFloat focusWidth = _headPic.height/2+5+size3.width;
//    _focus.frame = CGRectMake(SCREEN_WIDTH-10-focusWidth, _headPic.height/4+10, focusWidth, _headPic.height/2);
    CGFloat focusWidth = 10+size3.width+size3.height;
    _focus.frame = CGRectMake(SCREEN_WIDTH-10-focusWidth, 0, focusWidth,size3.height+8);
    _focus.centerY = _headPic.centerY;
    [_focus addTarget:self action:@selector(focusClick:) forControlEvents:UIControlEventTouchUpInside];
    
    _title = [[UILabel alloc] init];
    [_headBgView addSubview:_title];
    _title.font = kUHSystemFontWithSize(15);
    _title.lineBreakMode = NSLineBreakByWordWrapping;
    _title.textColor = kBlackColor;
    _title.numberOfLines = 0;
    _title.adjustsFontSizeToFitWidth = true;
    _title.lineBreakMode = NSLineBreakByTruncatingTail;
    _title.isCopyable = YES;
    
    _viewsCount = [[UILabel alloc] init];
    [_headBgView addSubview:_viewsCount];
    _viewsCount.font = kUHSystemFontWithSize(13);
    _viewsCount.textColor = kLightGrayColor;
    _viewsCount.layer.borderColor = UISeparatedColorRGB.CGColor;

    _money = [UIButton buttonWithType:UIButtonTypeCustom];
    [_headBgView addSubview:_money];
    _money.titleLabel.font = kUHSystemFontWithSize(13);
    _money.userInteractionEnabled = NO;
    [_money setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [_money setBackgroundImage:IMAGE(@"icon_bg_f60") forState:UIControlStateNormal];
    
    _sepView = [[UIView alloc] init];
    [_headBgView addSubview:_sepView];
    _sepView.backgroundColor = UISeparatedColorRGB;

    // 中部
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-49-64) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    //    _tableView.backgroundColor = kOrangeColor;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [[UIView alloc]init];
    
    [_tableView registerNib:[UINib nibWithNibName:@"QAZoneTableViewCell" bundle:nil] forCellReuseIdentifier:@"qaCell"];
    
    
    // 底部
    UIButton *postBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:postBtn];
    [postBtn setImage:IMAGE(@"icon_que_write_white") forState:UIControlStateNormal];
    [postBtn setTitle:@" 写回答" forState:UIControlStateNormal];
    [postBtn setBackgroundColor:UIMainColorRGB];
    postBtn.titleLabel.font = kUHSystemFontWithSize(14);
    postBtn.frame = CGRectMake(0, SCREEN_HEIGHT-49-64, SCREEN_WIDTH, 49);
    [postBtn addTarget:self action:@selector(inputAnswerClicK) forControlEvents:UIControlEventTouchUpInside];
    
    if ([self.isComment isEqualToString:@"1"]) {
        
//        [self inputAnswerClicK];
        
        if (GetUserDefaule(USERINFO) == NULL) {
            [self presentViewController:[LZCTools alertMessage:@"请先登录"]animated:YES completion:nil];
            return;
        }
        
        // 只有专家才能回答
        if ([_detailModel.scope isEqualToString:@"pro"]) {
            if (![[GetUserDefaule(USERINFO) valueForKey:@"role"] isEqualToString:@"3"]) {
                [self presentViewController:[LZCTools alertMessage:@"普通用户不能回答"] animated:YES completion:nil];
                return;
            }
        }
        
        PostsTextViewController *postVC = [[PostsTextViewController alloc] init];
        postVC.type = @"1";
        postVC.questionId = [NSString stringWithFormat:@"%ld", _detailModel.qId];
        [self presentViewController:postVC animated:YES completion:nil];
        
    }
    
    [self refreshData];
}

#pragma mark ==========更新数据==========
- (void)refreshData {
    __weak typeof (self) weakSelf = self;
    
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSLog(@"下拉刷新");
        weakSelf.page = 1;
        [weakSelf GETAnswers];
    }];
    
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        NSLog(@"上拉加载");
        weakSelf.page++;
        [weakSelf GETAnswers];
    }];
    
    
}

#pragma mark ==========UITableView==========
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    _cell = [tableView dequeueReusableCellWithIdentifier:@"qaCell"];
    _cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    Question *model = self.answerArr[indexPath.row];
    _cell.model = model;
    
    // 直接用问答主页的，所以cell样式需要修改
    _cell.line.hidden = YES;
    _cell.qaBtn.hidden = YES;
    _cell.praise.hidden = NO;
    _cell.disPraise.hidden = NO;

    // 赞
    if (model.is_like == 1) {
        [_cell.praise setImage:[IMAGE(@"index_zan_ed") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    }
    else
        [_cell.praise setImage:[IMAGE(@"index_zan") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [_cell.praise setTitle:[NSString stringWithFormat:@" %ld", model.likes_count] forState:UIControlStateNormal];
    // 踩
    if (model.is_unlike == 1) {
        [_cell.disPraise setImage:[IMAGE(@"index_yicai") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    }
    else
        [_cell.disPraise setImage:[IMAGE(@"question_cai") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [_cell.disPraise setTitle:[NSString stringWithFormat:@" %ld", model.unlikes_count] forState:UIControlStateNormal];
    
    CGSize size1 = [LZCTools textSizeWithText:_cell.viewNum.text font:_cell.viewNum.font];
    CGSize size2 = [LZCTools textSizeWithText:_cell.commentNum.text font:_cell.commentNum.font];
//    CGSize size3 = [LZCTools textSizeWithText:_cell.praise.titleLabel.text font:_cell.praise.titleLabel.font];
//    CGSize size4 = [LZCTools textSizeWithText:_cell.disPraise.titleLabel.text font:_cell.disPraise.titleLabel.font];
    
    CGFloat Y = _cell.viewNum.y;
    
    _cell.viewNum.frame = CGRectMake(10, Y, size1.width, size1.height);
//    _cell.praise.frame = CGRectMake(_cell.viewNum.x+_cell.viewNum.width+10, Y, size3.height+size3.width, size3.height);
//    _cell.disPraise.frame = CGRectMake(_cell.praise.x+_cell.praise.width, Y, size4.width+size4.height, size4.height);
    _cell.praise.frame = CGRectMake(_cell.viewNum.x+_cell.viewNum.width+10, Y, SW(8), size1.height);
    _cell.disPraise.frame = CGRectMake(_cell.praise.x+_cell.praise.width, Y, SW(8), size1.height);
    _cell.commentNum.frame = CGRectMake(_cell.disPraise.x+_cell.disPraise.width+10, Y, size2.width, size2.height);
    
    if (model.is_adopted==1) {
        [_cell.money setTitle:[NSString stringWithFormat:@"已赏%.2f元", [[model.author valueForKey:@"answer_price"] floatValue]/100] forState:UIControlStateNormal];
        CGSize size3 = [LZCTools textSizeWithText:_cell.money.titleLabel.text font:kUHSystemFontWithSize(13)];
        CGFloat moneyW = 10+size3.width;
        _cell.money.frame = CGRectMake(SCREEN_WIDTH-10-moneyW, 0, moneyW, size3.height+8);
        _cell.money.centerY = _cell.headPic.centerY;
        
        _cell.deleteBtn.frame = CGRectMake(SCREEN_WIDTH-_cell.headPic.width-10-_cell.money.width, 10, _cell.headPic.width, _cell.headPic.height);
        _cell.deleteBtn.centerY = _cell.headPic.centerY;
    }
    else {
        _cell.money.hidden = YES;
        
        _cell.deleteBtn.frame = CGRectMake(SCREEN_WIDTH-_cell.headPic.width, 10, _cell.headPic.width, _cell.headPic.height);
        _cell.deleteBtn.centerY = _cell.headPic.centerY;
    }
    
    
    if ([[GetUserDefaule(USERINFO) valueForKey:@"user_id"] isEqualToString:[model.author valueForKey:@"user_id"]]) {
        _cell.deleteBtn.hidden = NO;
        _cell.deleteBtn.tag = indexPath.row+10;
        [_cell.deleteBtn addTarget:self action:@selector(deleteCommentClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    else {
        _cell.deleteBtn.hidden = YES;
    }
    
    int state = [LZCTools thinkEnv];
    if (state == 0) {
        _cell.money.hidden = YES;
    }

    _cell.praise.tag = 1000+indexPath.row;
    _cell.disPraise.tag = 1000+indexPath.row;
    
    [_cell.praise addTarget:self action:@selector(praiseClick:) forControlEvents:UIControlEventTouchUpInside];
    [_cell.disPraise addTarget:self action:@selector(disPraiseClick:) forControlEvents:UIControlEventTouchUpInside];
    
    return _cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.answerArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat cellH = [_cell cellHeight];
    if (cellH == 0) {
        return 10;
    }
    else
        return [_cell cellHeight]-10;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"点击tableView.cell = %ld", indexPath.row);
    
    Question *model = self.answerArr[indexPath.row];
    
    
//    int state = [LZCTools thinkEnv];
//    if (state == 1) {
    
        if ([model.is_paid isEqualToString:@"N"] && [model.type isEqualToString:@"charge"]) {
            
            NSString *url = [NSString stringWithFormat:@"%@/%ld/purchases", APIQuestionsAnswers, model.qId];
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"付费后可观看答案" message:nil preferredStyle:UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"微信支付" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                [[NetworkTool sharedTool] requestWithName:@"付费观看答案" URLString:url parameters:@{@"channel":@"wx_app"} method:@"POST" callBack:^(id responseObject) {
                    [AliPayServer wxPay:responseObject[@"data"][@"param_obj"]];
                }];
                
            }]];
            [alert addAction:[UIAlertAction actionWithTitle:@"支付宝支付" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [[NetworkTool sharedTool] requestWithName:@"付费观看答案" URLString:url parameters:@{@"channel":@"ali_app"} method:@"POST" callBack:^(id responseObject) {
                    [AliPayServer aliPay:responseObject[@"data"][@"param_str"] memo:@"打赏成功"];
                }];
            }]];
            [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            }]];
            [self presentViewController:alert animated:YES completion:nil];
        }
//    }
    
    else {
        ReplyCommentViewController *replyVC = [[ReplyCommentViewController alloc] init];
        replyVC.questionId = model.qId;
        replyVC.type = 3;
    //    replyVC.qaUserId = [[_detailModel.author valueForKey:@"user_id"] integerValue];
    //    replyVC.questionIsClosed = _detailModel.is_closed;
        [self.navigationController pushViewController:replyVC animated:YES];
    }
}

#pragma mark ==========响应方法==========
- (void)GETAnswerDetail {
    
    NSString *url = [NSString stringWithFormat:@"%@/%@", APIQuestions, self.answerId];
    [[NetworkTool sharedTool] requestWithName:@"获取问题详情" URLString:url parameters:nil method:@"GET" callBack:^(id responseObject) {
        
        _detailModel = [[Question alloc] init];
        [_detailModel setValuesForKeysWithDictionary:responseObject[@"data"]];
        
        [self buildUI];
        
        [self postAssignment];
        
        [self GETAnswers];
    }];
    
}

- (void)postAssignment {
    
    [_headPic sd_setImageWithURL:[NSURL URLWithString:[_detailModel.author valueForKey:@"face"]] placeholderImage:IMAGE(@"placeHolder")];
    
    NSDictionary *user = [_detailModel valueForKey:@"author"];
    NSString *uid = [NSString stringWithFormat:@"%@", [_detailModel.author valueForKey:@"user_id"]];
    
    __weak typeof (self) weakSelf = self;
    
    [_headPic addActionWithblock:^{
        
        [PushPerHome pushPerHomeWithUserInfo:user];
    }];

    
    if ([[_detailModel.author valueForKey:@"role"] isEqualToString:@"1"]) {
        _role.image = IMAGE(@"");
    }
    else if ([[_detailModel.author valueForKey:@"role"] isEqualToString:@"2"]) {
        _role.image = IMAGE(@"icon_add_v");
    }
    else if ([[_detailModel.author valueForKey:@"role"] isEqualToString:@"3"]) {
        _role.image = IMAGE(@"icon_add_v_expert");
    }
    
    _nickName.text = [_detailModel.author valueForKey:@"nickname"];
    if ([[_detailModel.author valueForKey:@"sex"] intValue] == 1) {
        _gender.image = IMAGE(@"sex_boy");
    }
    else
        _gender.image = IMAGE(@"sex_girl");
    
    _date.text = _detailModel.human_time;
    
    if ([[GetUserDefaule(USERINFO) valueForKey:@"user_id"] isEqualToString:[_detailModel.author valueForKey:@"user_id"]]) {
        _focus.hidden = YES;
    }
    else
        _focus.hidden = NO;
    
    if ([[_detailModel.author valueForKey:@"is_like"] intValue] == 1) {
        [_focus setBackgroundImage:IMAGE(@"btn_concerned_bg") forState:UIControlStateNormal];
        [_focus setImage:[IMAGE(@"btn_ed_concern") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [_focus setTitle:@"已关注" forState:UIControlStateNormal];
    }
    else {
        [_focus setBackgroundImage:IMAGE(@"btn_unconcern_bg") forState:UIControlStateNormal];
        [_focus setImage:[IMAGE(@"btn_un_concern") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [_focus setTitle:@"  关注" forState:UIControlStateNormal];
    }
    
//    _title.text = _detailModel.body;
    _viewsCount.text = [NSString stringWithFormat:@"%ld浏览", _detailModel.views_count];
    if (_detailModel.is_closed==1) {
        [_money setTitle:[NSString stringWithFormat:@"已悬赏%.2f元", [[NSString stringWithFormat:@"%ld", _detailModel.reward] floatValue]/100] forState:UIControlStateNormal];
    }
    else
        [_money setTitle:@"未悬赏" forState:UIControlStateNormal];
    
    
    int state = [LZCTools thinkEnv];
    if (state == 0) {
        _money.hidden = YES;
    }
    
    // 布局
    CGSize size1 = [LZCTools textSizeWithText:_nickName.text font:_nickName.font];
    CGSize size2 = [LZCTools textSizeWithText:_title.text font:_title.font];
//    CGSize moodSize = [_title.text sizeWithFont:kUHSystemFontWithSize(13) constrainedToSize:CGSizeMake(SCREEN_WIDTH-_headPic.x*2, size2.height*1000) lineBreakMode:NSLineBreakByWordWrapping];
    
    _nickName.frame = CGRectMake(_headPic.x+_headPic.width+10, 10, size1.width, size1.height);
    _gender.frame = CGRectMake(_nickName.x+_nickName.width+5, 12, size1.height-4, size1.height-4);

    _title.text = _detailModel.body;
    NSMutableAttributedString *lsStr = [[NSMutableAttributedString alloc] initWithString:_title.text];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    [paragraphStyle setLineSpacing:4];//调整行间距
    [lsStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [_title.text length])];
    _title.attributedText = lsStr;
    CGSize moodSize = [_title.text boundingRectWithSize:CGSizeMake(SCREEN_WIDTH-_headPic.x*2, size2.height*1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:_title.font, NSParagraphStyleAttributeName:paragraphStyle, NSKernAttributeName:@1.5f} context:nil].size;

    _title.frame = CGRectMake(_headPic.x, _headPic.y+_headPic.height+10, SCREEN_WIDTH-_headPic.x*2, moodSize.height);
    
    CGFloat imgW = (SCREEN_WIDTH-40)/3;
    CGFloat imgY = _title.y+_title.height+10;
    CGFloat bottomY = _title.y+_title.height+10;
    
    for (int i = 0; i < _detailModel.pics.count; i++) {
        
        UIImageView *imgView = [[UIImageView alloc] init];
        [_headBgView addSubview:imgView];
        [imgView sd_setImageWithURL:[NSURL URLWithString:_detailModel.pics[i]] placeholderImage:IMAGE(@"placeHolder")];
        imgView.tag = 1+i;
        [imgView addTarget:self action:@selector(imageClick:)];
        imgView.contentMode = UIViewContentModeScaleAspectFill;
        imgView.clipsToBounds = YES;
        
        imgView.frame = CGRectMake(_headPic.x+(imgW+10)*i,imgY, imgW, imgW);
        
        bottomY = imgY+imgW+10;
    }
    
    _viewsCount.frame = CGRectMake(10, bottomY, SW(2), [LZCTools textSizeWithText:@"x" font:kUHSystemFontWithSize(13)].height);
    
    CGSize size4 = [LZCTools textSizeWithText:_money.titleLabel.text font:kUHSystemFontWithSize(13)];
    CGFloat moneyW = 10+size4.width;
    _money.frame = CGRectMake(SCREEN_WIDTH-10-moneyW, 0, moneyW, size4.height+8);
    _money.centerY = _viewsCount.centerY;
    
    _sepView.frame = CGRectMake(0, _viewsCount.y+_viewsCount.height+10, SCREEN_WIDTH, 10);
    
    CGFloat headH = _sepView.y+_sepView.height;
    // 如果有答案就显示
    if (_detailModel.answers_count > 0) {
        UILabel *answersNum = [[UILabel alloc] initWithFrame:CGRectMake(10, headH+10, SW(2), [LZCTools textSizeWithText:@"x" font:kUHSystemFontWithSize(13)].height)];
        [_headBgView addSubview:answersNum];
        answersNum.text = [NSString stringWithFormat:@"%ld个回答", _detailModel.answers_count];
        answersNum.textColor = kBlackColor;
        answersNum.font = kUHSystemFontWithSize(13);
        
        headH = answersNum.y+answersNum.height+10;
    }
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, headH, SCREEN_WIDTH, 1)];
    [_headBgView addSubview:line];
    line.backgroundColor = UISeparatedColorRGB;
    
    _headBgView.frame = CGRectMake(0, 0, SCREEN_WIDTH, headH+1);
    _tableView.tableHeaderView = _headBgView;
}

// 看大图
- (void)imageClick:(UIImageView *)img {
    
    UITapGestureRecognizer *tapRecognizer = (UITapGestureRecognizer
                                             *)img;
    LZPictureBrowser *mvc = [[LZPictureBrowser alloc] init];
    [mvc showWithPictureURLs:_detailModel.pics atIndex:[tapRecognizer.view tag]-1];
    
}

#pragma mark - 开始按钮响应方法
- (void)inputAnswerClicK {
    if (GetUserDefaule(USERINFO) == NULL) {
        [self presentViewController:[LZCTools alertMessage:@"请先登录"]animated:YES completion:nil];
        return;
    }
    
    // 只有专家才能回答
    if ([_detailModel.scope isEqualToString:@"pro"]) {
        if (![[GetUserDefaule(USERINFO) valueForKey:@"role"] isEqualToString:@"3"]) {
            [self presentViewController:[LZCTools alertMessage:@"普通用户不能回答"] animated:YES completion:nil];
            return;
        }
    }
    
    PostsTextViewController *postVC = [[PostsTextViewController alloc] init];
    postVC.type = @"1";
    postVC.questionId = [NSString stringWithFormat:@"%ld", _detailModel.qId];
    [self presentViewController:postVC animated:YES completion:nil];
}

// 获取评论
- (void)GETAnswers {
    
    NSString *url = [NSString stringWithFormat:@"%@/%@/answers", APIQuestions, self.answerId];
    NSDictionary *param = @{@"page":[NSString stringWithFormat:@"%ld", self.page],
                            @"per_page":@"10"};
    
    [[NetworkTool sharedTool] requestWithName:@"获取问题答案" URLString:url parameters:param method:@"GET" callBack:^(id responseObject) {
        
        NSArray *arr = responseObject[@"data"];
        
        if (self.page == 1) {
            [self.answerArr removeAllObjects];
        }
        if (arr.count == 0) {
            self.page--;
            if (self.page == 0) {
                self.page = 1;
            }
        }
        for (NSDictionary *dic in arr) {
            Question *model = [[Question alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.answerArr addObject:model];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
            [_tableView reloadData];
        });
    }];
    
}

// 关注
- (void)focusClick:(UIButton *)sender {
    
    NSString *toId = [_detailModel.author valueForKey:@"user_id"];
    
    [HomeServer focus:sender toId:toId];
}

// 删除答案
- (void)deleteCommentClick:(UIButton *)sender {
    
    Question *model = self.answerArr[sender.tag-10];
    NSString *replyId = [NSString stringWithFormat:@"%ld", model.qId];
    
    NSString *url = [NSString stringWithFormat:@"%@/%@", APIQuestionsAnswers, replyId];
    
    [[NetworkTool sharedTool] requestWithName:@"删除评论" URLString:url parameters:nil method:@"DELETE" callBack:^(id responseObject) {
        [self.answerArr removeObjectAtIndex:sender.tag-10];
        [_tableView reloadData];
    }];
    
}

// 点赞答案
- (void)praiseClick:(UIButton *)sender {
    Question *model = self.answerArr[sender.tag-1000];
    NSString *aId = [NSString stringWithFormat:@"%ld", model.qId];
    
    NSString *url = [NSString stringWithFormat:@"%@/%@/likes", APIQuestionsAnswers, aId];
    
    NSIndexPath *index = [NSIndexPath indexPathForRow:sender.tag-1000 inSection:0];
    QAZoneTableViewCell *cell = [_tableView cellForRowAtIndexPath:index];
    
    UIButton *otherBtn = cell.disPraise;
    
    [HomeServer praiseLogicCurrBtn:sender otherBtn:otherBtn url:url];
}
// 踩答案
- (void)disPraiseClick:(UIButton *)sender {
    Question *model = self.answerArr[sender.tag-1000];
    NSString *aId = [NSString stringWithFormat:@"%ld", model.qId];
    
    NSString *url = [NSString stringWithFormat:@"%@/%@/unlikes", APIQuestionsAnswers, aId];
    
    
    NSIndexPath *index = [NSIndexPath indexPathForRow:sender.tag-1000 inSection:0];
    QAZoneTableViewCell *cell  = [_tableView cellForRowAtIndexPath:index];
    
    UIButton *otherBtn = cell.praise;
    
//    [self praiseLogicCurrBtn:sender otherBtn:otherBtn url:url];
    [HomeServer praiseLogicCurrBtn:sender otherBtn:otherBtn url:url];
}

// 懒加载
- (NSMutableArray *)answerArr {
    if (_answerArr == nil) {
        _answerArr = [[NSMutableArray alloc] init];
    }
    return _answerArr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
